// @flow
import React from 'react'
import styles from './AddDevicePoint.css'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { Button, message } from 'antd'
import DevicePoint from 'components/DevicePointItem'

type Props = {
  history: Array<any>,
  location: Object
}
type States = {
  pointData: Array<Object>,
  partData: Array<Object>,
  devicePoint: Array<Object>,
  selectedRows: Array<Object>
}
class AddDevicePoint extends React.Component {
  props: Props
  state: States
  getPointData: Function
  goBack: Function
  getPartsData: Function
  getDevicePoint: Function
  changeSelectedRows: Function
  syncKMX: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      pointData: [],
      partData: [],
      devicePoint: [],
      selectedRows: []
    }
    this.getPointData = this.getPointData.bind(this)
    this.goBack = this.goBack.bind(this)
    this.getPartsData = this.getPartsData.bind(this)
    this.getDevicePoint = this.getDevicePoint.bind(this)
    this.syncKMX = this.syncKMX.bind(this)
    this.changeSelectedRows = this.changeSelectedRows.bind(this)
  }

  componentDidMount () {
    this.getPointData()
    this.getPartsData()
    this.getDevicePoint()
  }

  goBack () {
    history.go(-1)
  }

  changeSelectedRows (data) {
    this.setState({
      selectedRows: data
    })
  }

  syncKMX () {
    const { selectedRows } = this.state
    if (selectedRows.length === 0) {
      message.info('请选择至少一条元数据')
      return
    }
    selectedRows.map((d, i) => {
      universalFetch(`${__SERVICE_API__}device/kmx/limit2kmx?rid=${d.rid}`, {
        method: 'POST'
      })
        .then(res => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          this.getPointData()
          message.success('同步选中设置成功')
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
          message.error('同步选中设置失败: ' + error.message)
        })
    })
  }

  getDevicePoint () {
    universalFetch(`${__SERVICE_API__}device/templates/monitors/points`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({
          code: json.code,
          message: json.message
        }))
      }
      this.setState({
        devicePoint: json.result
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  getPointData () {
    const { data } = this.props.location.state
    let API = `${__SERVICE_API__}device/devices/points?root_id=${data.id}` // 设备
    if (data.parentId) { // 部件
      API = `${__SERVICE_API__}device/devices/points?root_id=${data.rootId}&device_id=${data.id}`
    }
    universalFetch(API)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({
          code: json.code,
          message: json.message
        }))
      }
      this.setState({
        pointData: json.result
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  getPartsData () {
    const { data } = this.props.location.state
    universalFetch(`${__SERVICE_API__}device/devices/${data.id}/boms?type=deep`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({
          code: json.code,
          message: json.message
        }))
      }
      this.setState({
        partData: json.result
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  render () {
    const { pointData, partData, devicePoint } = this.state
    const { data } = this.props.location.state
    return (
      <div className={styles['main']}>
        <section className={styles['header']}>
          <div className={styles['header-title']}>
            <span>名称: </span>
            <span>{data.name}</span>
          </div>
          <div className={styles['header-content']}>
            <span>客户: {data.customer ? data.customer.name : ''}</span>
            <span>类型: {data.type}</span>
            <span>型号: {data.spec}</span>
          </div>
          <div className={styles['setting']} title='设置'>
            <Button onClick={this.syncKMX} className={styles['settingBtn']} >同步选中设置</Button>
            <Button onClick={this.goBack} className={styles['settingBtn']} >返回</Button>
          </div>
        </section>
        <DevicePoint {...{
          location,
          pointData,
          partData,
          devicePoint,
          getPointData: this.getPointData,
          deviceId: data.id,
          rootId: data.rootId,
          rootName: data.name,
          changeSelectedRows: this.changeSelectedRows
        }} />
      </div>
    )
  }
}

export default AddDevicePoint
